<?php

namespace Summer\Hjd\Http\Controllers;

use Illuminate\Routing\Controller;
use RainLab\User\Models\User as UserModel;
use RLuders\JWTAuth\Classes\JWTAuth;
use Summer\Hjd\Classes\CommonApi;
use Summer\Hjd\Http\Requests\TfRecordCreateRequest;
use Summer\Hjd\Models\RgRecordModel;
use Summer\Hjd\Models\TfRecordModel;
use Summer\Hjd\Models\TfRuleModel;
use Summer\Hjd\Models\WalletModel;
use Summer\Hub\Http\Controllers\Traits\ApiReturn;
use Input;
use Config;
use Db;
use Exception;


class TfRecordController extends Controller
{
    use ApiReturn;
    /**
     * 充值申请
     * @param JWTAuth $auth
     * @param RgRecordRequest $request
     */
    public function create(JWTAuth $auth,TfRecordCreateRequest $request){
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $request->validate();
        $tf_rule_id=Input::get('tf_rule_id');
        $money=Input::get('money');
        $remark=Input::get('remark');
        //转账兑换规则
        $rule=TfRuleModel::with([
            'from_currency'=>function($q){
                $q->select('slug','title','price');
            },
            'to_currency'=>function($q){
                $q->select('slug','title','price');
            }
        ])->whereHas('from_currency',function ($q){
            $q->where('status',1);
        })->whereHas('to_currency',function ($q){
            $q->where('status',1);
        })->where('id',$tf_rule_id)->first();
        if(!$rule){
            return $this->apiError('转账兑换规则获取失败');
        }
        if($rule->status!=1){
            return $this->apiError('该转账兑换暂时关闭');
        }
        //金额限制
        if(($money<$rule->tf_min)&&($rule->tf_min>0)){
            return $this->apiError('最小转账兑换金额:'.$rule->tf_min);
        }
        if(($money>$rule->tf_max)&&($rule->tf_max>0)){
            return $this->apiError('最大转账兑换金额:'.$rule->tf_max);
        }
        if(($money%$rule->tf_mul!=0)&&($rule->tf_mul>0)){
            return $this->apiError($rule->tf_mul.'的整数倍转账兑换');
        }
        //余额判断
        $balance=WalletModel::where('currency_slug',$rule->from_currency_slug)->where('user_id',$user->id)->value('balance');
        if($money>$balance){
            return $this->apiError('余额不足');
        }

        if($rule->tf_type==1){//对外转账
            if(!Input::has('to_username')){
                return $this->apiError('请输入转入账号');
            }
            $to_username=Input::get('to_username');
//            $to_user_field='username';
            $to_user_field='userphone';
            $to_user=UserModel::where($to_user_field,$to_username)->first();
            if(!$to_user){
                return $this->apiError('转入用户不存在');
            }
            //转入用户的限制在此添加修改
            if($to_user->id==$user->id){
                return $this->apiError('不能给自己转账');
            }
            $to_user_id=$to_user->id;
        }
        if($rule->tf_type==2){//对内转换
            $to_user_id=$user->id;
        }
        $fmoney=$rule->from_currency->price*$money;
        $tmoney=$fmoney/$rule->to_currency->price;
        $fee=$tmoney*$rule->tf_fee*0.01;
        $to_money=$tmoney-$fee;
        $from_change_slug='transfer_red';
        $to_change_slug='transfer_add';
        Db::beginTransaction();
        try {
            $return=[];
            //创建转账兑换记录表
            $tf_record_table=new TfRecordModel();
            $tf_record_table->from_currency_slug=$rule->from_currency_slug;
            $tf_record_table->to_currency_slug=$rule->to_currency_slug;
            $tf_record_table->user_id=$user->id;
            $tf_record_table->relate_user_id=$to_user_id;
            $tf_record_table->money=$money;
            $tf_record_table->fee=$fee;
            $tf_record_table->to_money=$to_money;
            $tf_record_table->remark=$remark;
            $tf_record_table->tf_type=$rule->tf_type;
            $tf_record_table->status=1;
            $tf_record_table->save();
            //转账扣除
            $commonapi=new CommonApi();
            $commonapi->settleDetailed($user->id,$to_user_id,$money,0,$rule->from_currency_slug,[
                'change_slug'=>$from_change_slug,
                'table_id'=>$tf_record_table->id,
                'table_name'=>'summer_hjd_tf_record'

            ]);
            //转账增加
            $commonapi->settleDetailed($to_user_id,$user->id,$to_money,1,$rule->to_currency_slug,[
                'change_slug'=>$to_change_slug,
                'table_id'=>$tf_record_table->id,
                'table_name'=>'summer_hjd_tf_record'

            ]);
            Db::commit();
            return $this->apiSuccess('操作成功',$return);
        }catch (Exception $e) {
            Db::rollBack();
            return $this->apiError($e->getMessage());
        }
    }

    /**
     * 转账兑换记录
     */
    public function index(JWTAuth $auth)
    {
        if (!$user = $auth->user()) {
            return $this->apiError('登录失效,请重新登录');
        }
        $page=Input::get('page',1);
        $page_size=Input::get('page_size',20);
        $query=TfRecordModel::select();
        $query->with([
            'from_currency'=>function($q){
                $q->select('slug','title');
            },
            'to_currency'=>function($q){
                $q->select('slug','title');
            },
            'relate'=>function($q){
                $q->select('id','username','userphone','realname','nickname');
            },
        ]);
        if(Input::has('tf_type')){
            $tf_type=Input::get('tf_type');
            $query->where('tf_type',$tf_type);
        }
        if(Input::has('status')){
            $status=Input::get('status');
            $query->where('status',$status);
        }
        $query->where('user_id',$user->id);
        $query->orderBy('id','DESC');
        $records=$query->paginate($page_size,$page);
        $records->each(function ($record){
            $record->tf_type_text=Config::get('summer.hjd::tf_type.'.$record->tf_type);
        });
        $return['records']=$records;
        return $this->apiSuccess('操作成功',$return);
    }
}
